import fs from "fs";
import path from "path";
import { DataProps } from ".";
interface OneItemKeys {
  name?: string;
  alias?: string;
  description?: string;
  return?: string;
  // [PropName: string]: string; // 记录一下任意KEY
}
class GetElementInfoForTsFiles {
  result: OneItemKeys[] = [];
  private filePath: string;
  private getOneText = (): Promise<string[]> => {
    return new Promise((resolve) => {
      let resultArr: string[] = [];
      fs.readFile(this.filePath, "utf8", (err, data) => {
        if (err) throw err;
        const reg = new RegExp(/\/\*\*(\r\n\s\*\s@.*)*\r\n\s\*\//g, "g");
        let result: RegExpExecArray | null;
        while ((result = reg.exec(data)) != null) {
          resultArr.push(result[0]);
        }
        resolve(resultArr);
      });
    });
  };
  private parseSingleText = (text: string): OneItemKeys => {
    let result: RegExpExecArray | null;
    const reg = /@([a-z]*)\s(.*)/g;
    let obj: OneItemKeys = {};
    while ((result = reg.exec(text)) != null) {
      try {
        const key = RegExp.$1 as keyof OneItemKeys;
        const value = RegExp.$2;
        obj[key] = value;
      } catch (e) {
        console.log("读取文件发生错误");
      }
    }
    return obj;
  };
  private parseEndResult = (arr: string[]): Promise<OneItemKeys[]> => {
    return new Promise((resolve) => {
      let result = arr.map((e) => {
        return this.parseSingleText(e);
      });
      resolve(result);
    });
  };
  async init() {
    let oneArray = await this.getOneText();
    let result = await this.parseEndResult(oneArray);
    this.result = result;
    return this.result;
  }
  constructor(filePath: string) {
    this.filePath = filePath;
  }
  public getResult = () => this.result;
}
interface CreatElementDataProps {
  name: string;
  description: string;
  data: OneItemKeys[];
}
export async function creatElementData(
  dataArr: DataProps[]
): Promise<CreatElementDataProps[]> {
  let result: CreatElementDataProps[] = [];
  for (let i = 0; i < dataArr.length; i++) {
    const element = dataArr[i];
    const elementClass = new GetElementInfoForTsFiles(
      path.resolve(__dirname, `../common/${element.filePath}.ts`)
    );
    const obj = {
      name: element.name,
      description: element.description,
      data: await elementClass.init(),
    };
    result.push(obj);
  }
  return result;
}
